package com.example.uniapp01.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.client.RestTemplate;
import org.json.JSONObject;
import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/mdl")
public class UserController {

    @Autowired
    private RestTemplate restTemplate;

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody Map<String, String> body) {
        String code = body.get("code");
        Map<String, Object> result = new HashMap<>();
        if (code != null && !code.isEmpty()) {
            String openid = getOpenIdFromWeChat(code);
            if (openid != null && !openid.isEmpty()) {
                // 这里可查数据库，若无则新建用户
                Map<String, Object> user = new HashMap<>();
                user.put("nickname", "微信用户");
                user.put("avatar", "/static/logo.png");
                user.put("phone", "");
                user.put("gender", "");
                user.put("birthday", "");
                user.put("openid", openid);
                result.put("user", user);
                result.put("msg", "登录成功");
            } else {
                result.put("user", null);
                result.put("msg", "微信认证失败");
            }
        } else {
            result.put("user", null);
            result.put("msg", "code无效");
        }
        return result;
    }

    private String getOpenIdFromWeChat(String code) {
        try {
            String url = "https://api.weixin.qq.com/sns/jscode2session?appid=" + "wx3bc10a526f0ea043"
                    + "&secret=" + "073d29830456d3b35ea8ba7e83c9b166"
                    + "&js_code=" + code
                    + "&grant_type=authorization_code";
            String response = restTemplate.getForObject(url, String.class);
            JSONObject json = new JSONObject(response);
            return json.optString("openid", "");
        } catch (Exception e) {
            return "";
        }
    }
}
